package com.wxxymaker.model.dao;

import com.blade.ioc.annotation.Bean;
import com.blade.kit.StringKit;
import com.wxxymaker.model.entity.Article;
import com.wxxymaker.utils.Const;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.core.AnimaQuery;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;

import java.util.Map;

/**
 * @Author: Soft
 * @Date: 2018/6/29 23:44
 * @Desc: 文章Dao层
 */
@Bean
public class ArticleDao implements BaseDao<Article> {

    @Override
    public Article add(Article entity) {
        Integer key = entity.save().asInt();
        entity.setId(key);
        return entity;
    }

    @Override
    public Article delete(int id) {
        Article article = Anima.select().from(Article.class).byId(id);
        if (article != null) {
            Anima.deleteById(Article.class, id);
        }
        return article;
    }

    @Override
    public int change(Article entity) {
        return entity.updateById(entity.getId());
    }

    @Override
    public Article findOne(int id) {
        return Anima.select().from(Article.class).byId(id);
    }

    public Page<Article> page(int pageNo, int size, Map<String, Object> query) {
        AnimaQuery<Article> from = Anima.select().from(Article.class).order("id", OrderBy.DESC);
        if (query != null && !query.isEmpty()) {
            query.forEach((k, v)->{
                if (v instanceof String && !StringKit.isEmpty((String) v)) {
                    from.where(k, v);
                }
                if (v instanceof Integer && (int) v >= 0) {
                    from.where(k, v);
                }
            });
        }

        return from.page(pageNo, size);
    }

    public Page<Article> titleLike(String title) {
        return Anima.select().from(Article.class)
                .like(Article::getTitle, title + "%")
                .order("id", OrderBy.DESC)
                .page(1, Const.shortPageSize);
    }

    public void addLike(int id) {
        Anima.execute("update article set likes = likes + 1 where id=?", id);
    }

    public void addView(int id) {
        Anima.execute("update article set views = views + 1 where id=?", id);
    }
}
